package com.jcfk.eam.service.main;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jcfk.common.core.utils.IdUtils;
import com.jcfk.eam.domain.po.base.EamPlanRepairOrder;
import com.jcfk.eam.domain.po.base.EamRepairPlan;
import com.jcfk.eam.domain.po.base.EamRepairPlanDetail;
import com.jcfk.eam.domain.query.base.EamRepairPlanQuery;
import com.jcfk.eam.domain.dto.base.EamRepairPlanDTO;
import com.jcfk.eam.dao.base.EamRepairPlanDao;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.system.api.utils.CodeBuildUtils;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import com.jcfk.common.core.utils.BeanUtils;
import cn.hutool.core.util.StrUtil;
import com.jcfk.common.security.utils.SecurityUtils;
import com.alibaba.druid.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

import java.util.Date;
import java.util.stream.Collectors;

/**
 * 计划维修
 *
 * @author awei
 * @email 522891237@gqq.com
 * @date 2024-08-21
 */
@Service
public class EamRepairPlanService extends BaseService<EamRepairPlanDao, EamRepairPlan> {

    @Resource
    private EamRepairPlanDetailService eamRepairPlanDetailService;
    @Resource
    private EamPlanRepairOrderService eamPlanRepairOrderService;
    /**
     * EamRepairPlan分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamRepairPlanDTO> queryByPage(DataPage<EamRepairPlanDTO> page, EamRepairPlanQuery query) {
        // 分页查询
        query.setPlanCode(StringUtils.isEmpty(query.getPlanCode()) ? query.getPlanCode() : query.getPlanCode() + "%");
        query.setPlanName(StringUtils.isEmpty(query.getPlanName()) ? query.getPlanName() : query.getPlanName() + "%");
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }


    /**
     * 判断EamRepairPlan是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(EamRepairPlanDTO dto) {
        QueryWrapper<EamRepairPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        queryWrapper.eq("plan_code", dto.getPlanCode());
        if (!StringUtils.isEmpty(dto.getId())) queryWrapper.ne("id", dto.getId());
        Integer count = this.count(queryWrapper);

        if (count > 0) return RetResult.fail("计划编号已存在");
        return RetResult.ok();
    }

    /**
     * 插入计划维修
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(EamRepairPlanDTO dto) {

        // 保存
        EamRepairPlan item = new EamRepairPlan();
        BeanUtils.copyProperties(dto, item);

        this.setDefaultValue(item);
        item.setPlanStatus(0);

        super.save(item);
    }

    /**
     * 更新计划维修
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(EamRepairPlanDTO dto) {

        // 保存
        EamRepairPlan item = new EamRepairPlan();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);
    }

    /**
     * 根据批量主键删除计划维修(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(EamRepairPlanDTO dto) {

        EamRepairPlan item = new EamRepairPlan();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<EamRepairPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(EamRepairPlan item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setVersion(1L);
            item.setDeleted(0);
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

        item.setLastUpdatedUserName(SecurityUtils.getUserName());

    }

    /**
     * 根据主键获取计划维修信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EamRepairPlanDTO get(String id) {
        // 查询数据
        EamRepairPlan item = this.baseMapper.selectById(id);
        EamRepairPlanDTO dto = new EamRepairPlanDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }


    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<EamRepairPlanDTO>
     */
    public List<EamRepairPlanDTO> getList(EamRepairPlanQuery query) {
        // 查询条件
        QueryWrapper<EamRepairPlan> qw = new QueryWrapper<>();
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getPlanCode()), EamRepairPlan::getPlanCode, query.getPlanCode());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getPlanName()), EamRepairPlan::getPlanName, query.getPlanName());
        qw.lambda().eq(!StrUtil.isEmpty(query.getRepairType()), EamRepairPlan::getRepairType, query.getRepairType());
        qw.lambda().eq(!StrUtil.isEmpty(query.getDeviceDepartment()), EamRepairPlan::getDeviceDepartment, query.getDeviceDepartment());
        qw.lambda().eq(!StrUtil.isEmpty(query.getRepairDepartment()), EamRepairPlan::getRepairDepartment, query.getRepairDepartment());
        qw.lambda().in(CollUtil.isNotEmpty(query.getPlanStatus()), EamRepairPlan::getPlanStatus, query.getPlanStatus());
        qw.lambda().eq(query.getEnabled() != null, EamRepairPlan::getEnabled, query.getEnabled());
        qw.lambda().eq(query.getDeleted() != null, EamRepairPlan::getDeleted, query.getDeleted());
        qw.lambda().eq(query.getAssetKind() != null, EamRepairPlan::getAssetKind, query.getAssetKind());
        // 查询数据
        List<EamRepairPlan> list = super.list(qw);

        return convertList(list, EamRepairPlanDTO.class);
    }

    /**
     * 根据主键获取计划维修信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public void deleteItem(String id) {
        EamRepairPlan item = getById(id);
        this.setDefaultValue(item);
        item.setDeleted(1);

        this.updateById(item);
    }

    /**
     * 生成工单
     * @param id 维修计划id
     */
    @Transactional
    public void generateOrder(String id) {
        List<EamRepairPlanDetail> detailList = eamRepairPlanDetailService.list(Wrappers.<EamRepairPlanDetail>lambdaQuery()
                .eq(EamRepairPlanDetail::getPlanId, id)
                .eq(EamRepairPlanDetail::getDeleted, 0));
        Assert.notEmpty(detailList, "请先添加维修明细");
        EamRepairPlanDTO eamRepairPlanDTO = this.get(id);
        eamRepairPlanDTO.setPlanStatus(1);
        this.update(eamRepairPlanDTO);
        List<EamPlanRepairOrder> planRepairOrderList = detailList.stream().map(detail -> {
            EamPlanRepairOrder eamPlanRepairOrder = new EamPlanRepairOrder();
            eamPlanRepairOrderService.setDefaultValue(eamPlanRepairOrder);
            eamPlanRepairOrder.setPlanId(id);
            eamPlanRepairOrder.setPlanDetailId(detail.getId());
            eamPlanRepairOrder.setOrderNo(CodeBuildUtils.buildCode("planRepairOrder"));
            eamPlanRepairOrder.setRepairType(detail.getRepairType());
            eamPlanRepairOrder.setExecuteTeamId(detail.getExecuteTeamId());
            eamPlanRepairOrder.setExecuteTeamName(detail.getExecuteTeamName());
            eamPlanRepairOrder.setOrderStatus(0);
            eamPlanRepairOrder.setPlanStartTime(detail.getPlanStartTime());
            return eamPlanRepairOrder;
        }).collect(Collectors.toList());
        eamPlanRepairOrderService.saveBatch(planRepairOrderList);
    }
}

